import win32gui
import win32com.client
import time
import ctypes
dm=win32com.client.Dispatch("dm.dmsoft")
ret=dm.Reg("a89614291875cdb2d99ba0edbdddfbebd57b50c2b6","svk0sY8")
if ret==1:
    print('注册大漠成功')
else:
    print('大漠注册失败'+str(ret))
    exit()
print(dm.Ver())

dm.SetPath("D:/大漠图片/剪映图片")
def get_window_size(hwnd):
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    width = right - left
    height = bottom - top
    return width, height
def find_windows(class_name=None, title=None):
    hwnd_list = []

    def enum_callback(hwnd, _):
        current_class = win32gui.GetClassName(hwnd)
        current_title = win32gui.GetWindowText(hwnd)
        if (class_name is None or class_name == current_class) and \
                (title is None or title in current_title):
            hwnd_list.append(hwnd)
        return True

    win32gui.EnumWindows(enum_callback, None)
    return hwnd_list



import json
import random
import os
from moviepy import VideoFileClip

草稿路径=r"C:\Users\admin\AppData\Local\JianyingPro\User Data\Projects\com.lveditor.draft\\"
素材名字 ="美食开头"
模版名字="4月27日"
视频路径='D:/q/主页作品/Jessica Kaylee/视频作品/'
视频名字='#pov if you jinx with someone you have to knock on wood before the time runs out… PART 1 #povs #jinx #knockonwood cr @kitten_d.mp4'

def get_files(directory):
    return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

def 判断随机数(anum,videoname,nums):
    print('anum='+str(anum))
    print(videoname)

    while (True):
        数量 = len(videoname)
        #print(数量)
        if 数量==0:
           # print('跳出')
            return anum
        for index, item in enumerate(videoname) :
            #print("index"+str(index))
            if anum == item:
                #print('有重复')
                anum = random.randint(0, nums - 1)
                break
            if index == 数量-1:
                #print('没有重复'+str(index))
                return anum

def 生成josn(视频名字):

    with open(草稿路径+模版名字+r"\draft_content.json",encoding="utf-8") as files:
        file_contents = files.read()
       # print(file_content)
        files = get_files(视频路径)
        #print(files)
        with VideoFileClip(视频路径+视频名字) as video:
            读取视频持续时间=int(video.duration*1000000)
            print(读取视频持续时间)

        json_content = json.loads(file_contents)


        # 主轨道持续时间=json_content['tracks'][0]['segments'][0]['target_timerange']['duration']
        # print(主轨道持续时间)
        videonum=读取视频持续时间/6000000
        print(videonum)
        if videonum>15:
            return False
        c=读取视频持续时间%6000000
        print(c)

        if c>0:
            print('有余数')
            videonum=int(videonum)+1
            print(videonum)
        else:
            videonum=int(videonum)



    with open( 草稿路径+素材名字+r"\draft_content.json", encoding = "utf-8" ) as file:
        file_content = file.read()
       # print(file_content)
        json_content = json.loads(file_content)
        nums=len(json_content["materials"]['videos'])

        videoname=[]
        for i in range(videonum):
            rannum=random.randint(0, nums-1)
            rannums=判断随机数(rannum,videoname,nums)
            videoname.append(rannums)
        print(videoname)
        materials={'avideos':[],
                   'asegments':[]}

        for index,item in enumerate(videoname) :
            print(item)
            持续时间=json_content["tracks"][0]['segments'][item]['source_timerange']['duration']
            print(持续时间)
            json_content["tracks"][0]['segments'][item]['target_timerange']['start']=index*6000000
            json_content["tracks"][0]['segments'][item]['target_timerange']['duration']=6000000
            json_content["tracks"][0]['segments'][item]['source_timerange']['duration']=6000000
            json_content["tracks"][0]['segments'][item]['render_index']=1

            materials['avideos'].append(json_content["materials"]["videos"][item])
            materials['asegments'].append(json_content["tracks"][0]['segments'][item])

        # for index,a in enumerate(json_content["materials"]["videos"]) :
        #     if index == 1 :
        #         print('取出')
        #         print(a)
        #         print(json_content["materials"]["videos"][index]["material_name"])
        #         w=json_content["materials"]["videos"][index]
        #     #print(a["material_name"])
        # print(json_content['tracks'][0]['segments'][0]['material_id'])
        # for index,b in enumerate(json_content["tracks"][0]['segments']) :
        #     if index == 1 :
        #         print(b)
        #         d=b
        #         d["target_timerange"]['start']=0
        #         print(d["target_timerange"]['start'])
        #         print(d['material_id'])
    with open(草稿路径+模版名字+r"\draft_content.json",encoding="utf-8") as file:
        file_content = file.read()
        #print(json.dumps(file_content))
       # print(file_content)

        json_content = json.loads(file_content)
        json_content['tracks'][0]['segments'][0]['target_timerange']['duration']=读取视频持续时间
        # json_content['materials']['audios'][0]['duration']=读取视频持续时间 1
        # json_content['materials']['audios'][0]['name']=视频名字 1
        # json_content['materials']['audios'][0]['path']=视频路径+视频名字 1
        json_content['duration']=读取视频持续时间

        print('666666666666'+视频名字)
        #json_content['tracks'][2]['segments'][0]['source_timerange']['duration']=读取视频持续时间 1
       # json_content['tracks'][2]['segments'][0]['target_timerange']['duration'] = 读取视频持续时间 1
        json_content['materials']['videos'][0]['path']=视频路径+视频名字
        json_content['materials']['videos'][0]['material_name']=视频名字
        json_content['materials']['videos'][0]['duration']


        主轨道持续时间=json_content['tracks'][0]['segments'][0]['target_timerange']['duration']
        print(主轨道持续时间)
        json_content['tracks'][1]['segments'][0]['source_timerange']['duration']=主轨道持续时间
        json_content['tracks'][1]['segments'][0]['target_timerange']['duration']=主轨道持续时间
        json_content['materials']['videos'][1]['duration']=主轨道持续时间
        print(json_content["materials"]['videos'][0]["path"])

        json_content['materials']['drafts'][0]['draft']['materials']['videos'].clear()

        for index,item in  enumerate(materials['avideos']):
            #print(index)
            #json_content['materials']['drafts'][0]['draft']['materials']['videos'].get(index)

            json_content['materials']['drafts'][0]['draft']['materials']['videos'].append(item)
            #print(item['material_name'])
        # json_content['materials']['drafts'][0]['draft']['materials']['videos'][0]=w
        # print(w['material_name'])


        json_content['materials']['drafts'][0]['draft']['tracks'][1]['segments'].clear()

        for index,item in enumerate(materials['asegments']) :
            json_content['materials']['drafts'][0]['draft']['tracks'][1]['segments'].append(item)


        # json_content['materials']['drafts'][0]['draft']['tracks'][1]['segments'][0]=d
        # print(json_content['tracks'][1]['segments'][0]['material_id'])
        # json_content['tracks'][1]['segments'][0]=d
        with open(r'C:\Users\admin\AppData\Local\JianyingPro\User Data\Projects\com.lveditor.draft\4月27日\draft_content.json',"w",encoding="utf-8") as f:
            json.dump(json_content,f,ensure_ascii=False,indent=4)
            print('导出成功')





def 剪映大漠操作():
    hwnd=dm.FindWindow('Qt622QWindowIcon','剪映专业版')
    if hwnd==0:
        print('没有找到窗口')
        exit()
    print(hwnd)
    isbind=dm.BindWindowEx(hwnd,"dx.graphic.3d.10plus","windows","windows","",0)
    #isbind=dm.BindWindowEx(hwnd,"normal","windows","windows","",0)
    print(isbind)
    if isbind==0:
        print('大漠绑定失败')
        print(dm.GetLastError())
    time.sleep(2)
    intX=0
    intY=0
    while True:

        dm_ret = dm.FindPic(754,221,851,302,"1.bmp","000000",0.9,0,intX,intY)
        if dm_ret[1] >= 0 and dm_ret[2] >= 0:
            print('放大镜')
            dm.MoveTo(dm_ret[1],dm_ret[2])
            time.sleep(0.1)
            dm.LeftClick()
            time.sleep(1.5)


        dm_ret = dm.FindPic(555,231,717,278,"搜索名称.bmp","000000",0.9,0,intX,intY)

        if dm_ret[1] >= 0 and dm_ret[2] >= 0:
            print('搜索名称')
            ret=dm.SendString(hwnd,模版名字)
            if ret==1:
                print('发送成功')

        dm_ret = dm.FindPic(465,65,791,132,"开始创作.bmp","000000",0.9,0,intX,intY)
        if dm_ret[1] >= 0 and dm_ret[2] >= 0:
            print('开始创作')

            dm_ret = dm.FindPic(299,90,685,642,"黑框.bmp","000000",0.9,0,intX,intY)

            if dm_ret[1] >= 0 and dm_ret[2] >= 0:
                print('黑框')
                dm.MoveTo(286,341)
                time.sleep(0.1)
                dm.LeftClick()
                time.sleep(2)

        ret = find_windows('Qt622QWindowIcon', '剪映专业版')

        if len(ret) > 1:
            print('小窗口消失')
            dm_ret = dm.UnBindWindow()
            print(str(dm_ret)+'取消绑定')
            time.sleep(2)
            break
    for i in range(5):
        ret=find_windows('Qt622QWindowIcon','剪映专业版')
        print(ret)
        if len(ret)>1:
            for hwnd in ret:
                print(hwnd)
                width, height= get_window_size(hwnd)
                print(width, height)
                if width>1200:
                    hwnds=hwnd
                    print('hwnds='+str(hwnds))
                    break

            isbind = dm.BindWindowEx(hwnds, "normal", "normal", "dx.keypad.input.lock.api|dx.keypad.state.api|dx.keypad.api", "", 0)

            print(isbind)
            if isbind != 1:
                print("大窗口大漠绑定失败")
                exit()
            else:
                print('大窗口大漠绑定成功')
                time.sleep(2)
                break
            time.sleep(1)
    dm.KeyDown(17)
    time.sleep(1)
    dm.KeyDown(69)
    time.sleep(0.5)
    dm.KeyUp (17)
    dm.KeyUp(69)
    time.sleep(3)
    dm.KeyPress(13)
    time.sleep(3)
    for i in range(60):
        dm_ret = dm.FindPic(644,562,1035,769, "关闭.bmp", "000000", 0.9, 0, intX, intY)
        if dm_ret[1] >= 0 and dm_ret[2] >= 0:
            print('关闭')
            dm.MoveTo(dm_ret[1], dm_ret[2])
            time.sleep(0.1)
            dm.LeftClick()
            time.sleep(2)
        dm_ret = dm.FindPic(1246,4,1277,62, "关闭大窗口.bmp", "000000", 0.9, 0, intX, intY)
        if dm_ret[1] >= 0 and dm_ret[2] >= 0:
            print('关闭大窗口')
            dm.MoveTo(dm_ret[1], dm_ret[2])
            time.sleep(0.1)
            dm.LeftClick()
            time.sleep(2)
            dm.UnBindWindow()
            time.sleep(2)
            break
        time.sleep(1)


                # for item in file_content1:
                #     print(item):


# print(file_content)
files = get_files(视频路径)
for item in files:
    if 生成josn(item)==False:
        continue
    剪映大漠操作()
    print(item)
# for i in range(5):
#     ret=dm.FindWindow('Qt622QWindowIcon','导出')
#     if ret!=0:
#         dchwnd=ret
#         dm_ret = dm.UnBindWindow()
#         print(str(dm_ret)+'大窗口取消绑定')
#         time.sleep(2)
#         isbind = dm.BindWindowEx(dchwnd, "normal", "windows",
#                                  "normal", "", 0)
#         time.sleep(2)
#
#
#
#         print(isbind)
#         break
#     time.sleep(1)
